package com.ctg.behavior.calc.impala.builder.tracks;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.stereotype.Component;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.ctg.behavior.common.consts.CtFieldConsts;
import com.ctg.behavior.common.tracks.CtTracksBody;
import com.ctg.behavior.common.tracks.CtTracksData;
import com.ctg.behavior.common.tracks.CtTracksResult;
import com.ctg.behavior.utils.CtDateUtils;
import com.ctg.behavior.utils.CtStringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtTracksCalcResultBuilder {

	public CtTracksResult doBuilder(CtTracksResult tracksResult, List<LinkedHashMap<String, Object>> calcResult, CtTracksBody tracksCalcBody) {

		tracksResult.getValue().setAppId(tracksCalcBody.getAppId());
		tracksResult.getValue().setBookmarkId(tracksCalcBody.getBookmarkId());
		tracksResult.getValue().setRequestId(tracksCalcBody.getRequestId());

		tracksResult.getValue().setReportUpdateTime(CtDateUtils.dateToString(new Date()));
		tracksResult.getValue().setDataUpdateTime(CtDateUtils.dateToString(new Date()));

		tracksResult.getValue().setCurrentPage(tracksCalcBody.getCurrentPage());
		tracksResult.getValue().setPageSize(tracksCalcBody.getPageSize());

		for (LinkedHashMap<String, Object> oneRow : calcResult) {
			String eventId = String.valueOf(oneRow.get(CtFieldConsts.FIELD_KEY_EVENT));
			String userId = String.valueOf(oneRow.get(CtFieldConsts.FIELD_USER_ID));
			String trackId = String.valueOf(oneRow.get(CtFieldConsts.FIELD_TRACK_ID));
			String bdScenceId = String.valueOf(oneRow.get(CtFieldConsts.FIELD_BD_SCENCE_ID));
			String enventTime = String.valueOf(oneRow.get(CtFieldConsts.FIELD_KEY_EVENT_TIME));
			
			if (CtStringUtils.isEmpty(eventId)
					||CtStringUtils.isEmpty(userId)
					||CtStringUtils.isEmpty(trackId)
					||CtStringUtils.isEmpty(bdScenceId)
					||CtStringUtils.isEmpty(enventTime)
					) {
				log.error("calcResult-oneRow:{}", JSON.toJSONString(oneRow));
			}
			
			CtTracksData calcData = new CtTracksData();
			calcData.setEventId(eventId);
			calcData.setUserId(userId);
			calcData.setTrackId(trackId);
			calcData.setBdScenceId(bdScenceId);
			if(!StringUtils.isEmpty(enventTime)) {
				String time = CtDateUtils.dateToString(new Date(Long.parseLong(enventTime)));
				calcData.setTime(time);
			}
			
			calcData.setContent(JSON.toJSONString(oneRow));
			
			tracksResult.getValue().getList().add(calcData);
		}

		return tracksResult;

	}
}
